package moe.oil.db.service;

import lombok.Setter;
import moe.oil.dto.user.UserTargetDTO;
import moe.oil.db.entity.UserTarget;
import moe.oil.db.repo.UserTargetRepo;
import moe.oil.exception.usertarget.UserTargetIdNullException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/16 16:48
 * Description:
 *
 * @author - -
 */
@Service
@Setter(onMethod_ = @Autowired)
public class UserTargetService implements BaseService {

    private UserTargetRepo userTargetRepo;

    // 添加用户目标
    public Optional<UserTargetDTO> add(UserTargetDTO userTargetDTO) {
        return Optional.of(userTargetRepo.save(new UserTarget(userTargetDTO)).convert());
    }

    // 根据ID查询用户目标
    public Optional<UserTargetDTO> findById(Long id) {
        if (id != 0) {
            return Optional.of(userTargetRepo.findByTargetId(id).orElseThrow(() -> new UserTargetIdNullException(id)).convert());
        } else {
            throw new UserTargetIdNullException(id);
        }

    }

    // 查询全部用户目标
    public List<UserTargetDTO> findAll(PageRequest pageRequest) {
        return userTargetRepo.findAll(pageRequest)
                .stream().map(UserTarget::convert)
                .collect(java.util.stream.Collectors.toList());
    }

    // 删除用户目标
    public int deleteById(Long id) {

        if (id != 0) {
            return userTargetRepo.deleteByTargetId(id);
        } else {
            throw new UserTargetIdNullException(id);
        }
    }

    // 修改用户目标
    public Optional<UserTargetDTO> update(UserTargetDTO userTargetDTO) {
        var id = userTargetDTO.getUserTargetId();
        if (id != 0) {
            return Optional.of(userTargetRepo.save(new UserTarget(userTargetDTO)).convert());
        } else {
            throw new UserTargetIdNullException(id);
        }
    }
}